package cn.geminis.warehouse.service.purchase.controller;

import cn.geminis.warehouse.service.basic.entity.Product;
import cn.geminis.warehouse.service.basic.entity.ProductBatch;
import cn.geminis.warehouse.service.purchase.entity.filter.PurchaseDetailFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;
import java.util.stream.Collectors;

public class PurchaseDetailController {

    @PostMapping("scan/{purchaseId}/{productNo}")
    public void scan(@PathVariable String purchaseId, @PathVariable String productNo) {
        var details = this.repository
                .findAll(
                        PurchaseDetailFilter.builder()
                                .purchaseId(purchaseId)
                                .productBatchProductNo(productNo)
                                .build()
                );
        if (details.isEmpty()) {
            throw new RuntimeException("入库单不包含该商品，编码：" + productNo);
        }
        var detail = details.stream().filter(purchaseDetail -> purchaseDetail.getAmount() > purchaseDetail.getAmountScan()).findAny();
        detail.ifPresentOrElse((data) -> {
                    data.setAmountScan(data.getAmountScan() + 1);
                    this.repository.save(data);
                },
                () -> {
                    throw new RuntimeException("该商品数量已达上线，编码：" + productNo);
                });
    }

    @GetMapping("{purchaseId}/product")
    public List<Product> getPurchaseProduct(@PathVariable String purchaseId) {
        return this.repository
                .findAll(
                        PurchaseDetailFilter.builder()
                                .purchaseId(purchaseId)
                                .include(new String[]{"productBatch.product"})
                                .build()
                )
                .stream().map(detail -> detail.getProductBatch().getProduct())
                .collect(Collectors.toList());
    }

    @GetMapping("{purchaseId}/{productId}/batch")
    public List<ProductBatch> getOrderInProductBatch(@PathVariable String purchaseId, @PathVariable String productId) {
        return this.repository
                .findAll(
                        PurchaseDetailFilter.builder()
                                .purchaseId(purchaseId)
                                .productBatchProductId(productId)
                                .include(new String[]{"productBatch"})
                                .build()
                )
                .stream().map(detail -> detail.getProductBatch())
                .collect(Collectors.toList());
    }
}
